package com.lcf.user.controller;

import com.lcf.user.constant.CookieConstant;
import com.lcf.user.constant.RedisConstant;
import com.lcf.user.constant.ResultEnum;
import com.lcf.user.constant.RoleEnum;
import com.lcf.user.entity.User;
import com.lcf.user.service.UserService;
import com.lcf.user.utils.CookieUtil;
import com.lcf.user.utils.ResultVoUtils;
import com.lcf.user.vo.ResultVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/buyer")
    public ResultVo buyer(@RequestParam("openid") String openid, HttpServletResponse response) {
        //1.判断用户是否存在
        User user = userService.findUserByOpenid(openid);
        if (null == user) {
            return ResultVoUtils.error(ResultEnum.LOGIN_FAIL);
        }

        //2.判断角色
        if (!RoleEnum.BUYER.getCode().equals( user.getRole())) {
            return ResultVoUtils.error(ResultEnum.ROLE_ERROR);
        }

        //3.往cookie里设置值
        CookieUtil.set(response, CookieConstant.OPENID, openid, CookieConstant.EXPIRE);

        return ResultVoUtils.success();
    }


    @GetMapping("/seller")
    public ResultVo seller(@RequestParam("openid") String openid, HttpServletResponse response, HttpServletRequest request) {
        String var1 = CookieUtil.get(request, CookieConstant.TOKEN);
        if(null!=var1
                && StringUtils.isNotBlank(stringRedisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_UUID,var1)))
        ){
            return ResultVoUtils.success();
        }

        //1.判断用户是否存在
        User user = userService.findUserByOpenid(openid);
        if (null == user) {
            return ResultVoUtils.error(ResultEnum.LOGIN_FAIL);
        }

        //2.判断角色
        if (!RoleEnum.SELLER.getCode().equals( user.getRole())) {
            return ResultVoUtils.error(ResultEnum.ROLE_ERROR);
        }

        //3.往redis里设置值key = uuid
        String key = String.format(RedisConstant.TOKEN_UUID, UUID.randomUUID().toString().replace("-", ""));
        stringRedisTemplate.opsForValue().set(key, openid, RedisConstant.EXPIRE, TimeUnit.SECONDS);
        //4.往cookie里设置值
        CookieUtil.set(response, CookieConstant.TOKEN, key, CookieConstant.EXPIRE);

        return ResultVoUtils.success();
    }

}
